
import {globalCache} from "./globalCache";

let geoUtils = {
    /**
     *  判断是否是逆时针
     * @param x1
     * @param y1
     * @param x2
     * @param y2
     * @param x3
     * @param y3
     * @return {boolean}
     * @private
     */
    isCCW(x1, y1, x2, y2, x3, y3) {
        let ab = globalCache.get_v2();
        ab.x = x2 - x1;
        ab.y = y2 - y1;

        let ac = globalCache.get_v2();
        ac.x = x3 - x1;
        ac.y = y3 - y1;

        let cross = ab.x * ac.y - ab.y * ac.x;
        globalCache.put_v2(ab);
        globalCache.put_v2(ac);
        return cross > 0;
    },


    // 根据顶点和索引信息计算法线
    calNormals(vertexs,indices){
        let normals = new Array(vertexs.length);
        // 手工计算顶点法线
        let all = {};
        let faceCount = Math.floor(indices.length / 3);
        let v01 = cc.v3();
        let v12 = cc.v3();
        let v0 = cc.v3();
        let v1 = cc.v3();
        let v2 = cc.v3();
        let tmpNormal = cc.v3();
        for(let i = 0; i < faceCount; ++i){
            let i0 = indices[3 * i];
            let i1 = indices[3 * i + 1];
            let i2 = indices[3 * i + 2];
            cc.Vec3.set(v0,vertexs[3 * i0],vertexs[3 * i0 + 1],vertexs[3 * i0 + 2]);
            cc.Vec3.set(v1,vertexs[3 * i1],vertexs[3 * i1 + 1],vertexs[3 * i1 + 2]);
            cc.Vec3.set(v2,vertexs[3 * i2],vertexs[3 * i2 + 1],vertexs[3 * i2 + 2]);

            cc.Vec3.subtract(v01,v1,v0);
            cc.Vec3.subtract(v12,v2,v1);
            cc.Vec3.cross(tmpNormal,v01,v12);
            cc.Vec3.normalize(tmpNormal,tmpNormal);
            if(!all[i0]){
                all[i0] = [];
            }
            all[i0].push([tmpNormal.x,tmpNormal.y,tmpNormal.z]);

            if(!all[i1]){
                all[i1] = [];
            }
            all[i1].push([tmpNormal.x,tmpNormal.y,tmpNormal.z]);

            if(!all[i2]){
                all[i2] = [];
            }
            all[i2].push([tmpNormal.x,tmpNormal.y,tmpNormal.z]);
        }

        //  求平均值
        for(let k in all){
            let idx = parseInt(k);
            let arr = all[k];
            let dlen = 1 / (arr.length || 1);
            let x = 0,y = 0,z = 0;
            arr.forEach(item=>{
                x += item[0];
                y += item[1];
                z += item[2];
            });

            cc.Vec3.set(tmpNormal,x * dlen, y * dlen,z * dlen);
            cc.Vec3.normalize(tmpNormal,tmpNormal);

            normals[3 * idx] = tmpNormal.x;
            normals[3 * idx + 1] = tmpNormal.y;
            normals[3 * idx + 2] = tmpNormal.z;
        }

        return normals;
    }
};

export default geoUtils;
